﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Net;
using Pavilion.Communications;

namespace Pavilion.Communications
{
    public class DataTransferClient : BaseClient
    {
        private static DataTransferClient instance;
        static public DataTransferClient Instance { get { return (instance == null) ? new DataTransferClient() : instance; } }

        public Action TransferDataAction { get; set; }
        public IUpdateGameService Proxy { get { return (IUpdateGameService)proxy; } }

        private System.Diagnostics.Process process;

        public DataTransferClient()
        {
            instance = this;

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "PavilionGame.exe";

            base.Initialize(8000);
        }

        protected override ICommunicationObject CreateProxy(NetTcpBinding tcpBinding, EndpointAddress endpointAddress)
        {
            return (ICommunicationObject)ChannelFactory<IUpdateGameService>.CreateChannel(tcpBinding, endpointAddress);
        }

        protected override void CloseCommunication()
        {
            base.CloseCommunication();

            if (!process.HasExited)
            {
                try { process.CloseMainWindow(); }
                catch { }
            }
        }

        protected override void OpenCommunication()
        {
            process.Close();
            process.Start();

            base.OpenCommunication();

            FullDataTransfer();
        }

        public void FullDataTransfer()
        {
            if (ConnectionStatus != ConnectionStatus.Open)
                return;

            Proxy.BeginDataTransfer();
            TransferDataAction.Invoke();
            Proxy.EndDataTransfer();
        }

        public void TransferData(Func<IUpdateGameService, string> action)
        {
            if (ConnectionStatus != ConnectionStatus.Open)
                return;

            try
            {
                string errorMessage = action.Invoke(Proxy);

                if (errorMessage != "")
                    throw new Exception(errorMessage);
            }
            catch { }
        }

        public void TransferData(Action<IUpdateGameService> action)
        {
            if (ConnectionStatus != ConnectionStatus.Open)
                return;

            try { action.Invoke(Proxy); }
            catch { }
        }
    }
}
